package com.tju.resource.business.tb_sharper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbMaterialMapper;
import com.tju.resource.mapper.TbSharperMapper;
import com.tju.resource.model.TbMaterial;
import com.tju.resource.model.TbSharper;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.result.SimpleXls;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class TbSharperServiceImpl extends ServiceImpl<TbSharperMapper, TbSharper>
        implements TbSharperService {
    @Autowired
    private TbSharperMapper mapper;
    @Autowired
    private ChineseExceptionUtils zh_CH;
    @Autowired
    private TbMaterialMapper tbMaterialMapper;
    @Autowired
    private TbSharperService tbSharperService;

    @Override
    public Result<Object> selectTbSharper(ClientParameters pa) {
        try {
            Integer pageNum = pa.getPage();//页码
            Integer pageSize = pa.getLimit(); //页数
            if (EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)) {
                pageNum = pageNum == 0 ? 1 : pageNum; //默认值
                pageSize = pageSize == 0 ? 10 : pageSize;//默认值
                Page<TbSharper> page = new Page<>(pageNum, pageSize);//分页
                IPage<TbSharper> iPage = mapper.selectTbSharper(page, pa);
                return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    @Override
    @Transactional
    public Result<Object> insertTbSharper(TbSharper tbSharper) {
        //String sharperName = tbSharper.getSharperName();//磨具名称
        try {
            String sharperSerialNumber = tbSharper.getSharperSerialNumber();//磨具编号
            if (EmptyUtils.isNotEmpty(sharperSerialNumber)) {
                if (EmptyUtils.isNotEmpty(checkSharperNameUnique(null, sharperSerialNumber)))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不能重复模具编号！");
            }
            if (EmptyUtils.isNotEmpty(tbSharper.getResidualLife()) && EmptyUtils.isNotEmpty(tbSharper.getInitialLife())) {
                if (tbSharper.getResidualLife() > tbSharper.getInitialLife()) {
                    throw new ServiceException("初始寿命必须要大于剩余寿命！");
                }
            }
            if (mapper.insert(tbSharper) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.AddedSuccessfully);
            }
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.AddFailed);
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Object> updateTbSharper(TbSharper tbSharper) {
        try {
            TbSharper tb = mapper.selectById(tbSharper.getId()); //查询磨具
            if (EmptyUtils.isEmpty(tb)) {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不存在该模具！");
            }
            if (EmptyUtils.isNotEmpty(tbSharper.getResidualLife()) && EmptyUtils.isNotEmpty(tbSharper.getInitialLife())) {
                if (tbSharper.getResidualLife() > tbSharper.getInitialLife()) {
                    throw new ServiceException("初始寿命必须要大于剩余寿命！");
                }
            }
            //String sharperName = tbSharper.getSharperName();//磨具名称
            String sharperSerialNumber = tbSharper.getSharperSerialNumber();//磨具编号
//            if (!tb.getSharperName().equals(sharperName)) {
//                if (EmptyUtils.isNotEmpty(checkSharperNameUnique(sharperName, null))) {
//                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "模具名称重复！");
//                }
//            }
            if (tbSharper.getResidualLife() > tbSharper.getInitialLife()) {
                throw new ServiceException("初始寿命必须要大于剩余寿命！");
            }
            if (EmptyUtils.isNotEmpty(sharperSerialNumber)) {
                if (!tb.getSharperSerialNumber().equals(sharperSerialNumber)) {
                    if (EmptyUtils.isNotEmpty(checkSharperNameUnique(null, sharperSerialNumber))) {
                        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "模具编号重复！");
                    }
                }
            }
            if (mapper.updateById(tbSharper) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyModified);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailToEdit);
    }

    @Override
    @Transactional
    public Result<Object> deleteTbSharper(TbSharper tbSharper) {
        try {
            if (EmptyUtils.isNotEmpty(tbSharper.getId())) {
                QueryWrapper<TbMaterial> qw = new QueryWrapper<>();
                qw.eq("sid", tbSharper.getId());
                if (EmptyUtils.isNotEmpty(tbMaterialMapper.selectList(qw))) {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "该模具被使用了不能删除！");
                }
                //不存在就删除
                if (mapper.deleteById(tbSharper.getId()) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyDeleted);
                }
            } else {
                ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailedToDelete);
    }
    public static final Map<String, String> keyToBean = new HashMap<>() {{
        put("模具编号", "sharperSerialNumber");
        put("模具名称", "sharperName");
        put("初始寿命", "initialLife");
        put("剩余寿命", "residualLife");
        put("穴数", "holeNum");
        put("模具维修次数", "sharperMaintainCount");
        put("开模日期", "dieOpenTime");
        put("模具维修时间", "sharperMainiainTime");
        put("备注", "remark");
        put("模具维修描述", "sharperMainiainDepict");
        put("模胚尺寸", "sizeDesc");
        put("模具仁料", "kernel");
        put("模具费", "cost");
    }};
    /**
     * 导入模具
     */
    @Override
    @Transactional
    public Result<Object> importSharper(Map<String, String> map, MultipartFile file) {
        if (!file.isEmpty()) {  //文件
            try {
                if (EmptyUtils.isEmpty(file.getOriginalFilename())) {  //判断文件名不为空
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "文件名不存在");
                }
                String originalFilename = file.getOriginalFilename(); //拿到文件名
                String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); //拿到后缀
                if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "请选择excel文件");
                }
                return SimpleXls.saveAsBeans(
                        TbSharper.class
                        , keyToBean
                        , file.getInputStream()
                        , tbSharperService::insertTbSharper, tbSharper -> tbSharper.setCreateBy(map.get("createBy")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "请选择文件");
    }

    /**
     * 判断唯一的磨具名称和编号
     *
     * @param
     * @return
     */
    public TbSharper checkSharperNameUnique(String sharperName, String sharperSerialNumber) {
        QueryWrapper<TbSharper> qw = new QueryWrapper<>();
        if (EmptyUtils.isNotEmpty(sharperName)) {
            qw.eq("sharper_name", sharperName).or();
        }
        if (EmptyUtils.isNotEmpty(sharperSerialNumber)) {
            qw.eq("sharper_serial_number", sharperSerialNumber);
        }
        List<TbSharper> tbSharpers = mapper.selectList(qw);
        for (TbSharper tbSharper : tbSharpers) {
            if (EmptyUtils.isNotEmpty(tbSharper)) {
                return tbSharper;
            }
        }
        return null;
    }
}
